// project created on 11/04/2007 at 12:42
using System;
using System.Data;
using System.Data.SqlClient;
using Db4objects.Db4o;

namespace TypingMonkey
{
	class MainClass
	{
		public static Typewriter tw;
		public static bool off;
		public static string[] targets;
		public static SqlCommand sql;
		public static int count;

		public static void Main(string[] args)
		{
			count = int.Parse(args[0]);
			ClearDatabase();
			/// Init SQL ///
			sql = new SqlCommand();
			sql.Parameters.Add("@seq", SqlDbType.NVarChar);
			sql.Parameters.Add("@iter", SqlDbType.BigInt);
			sql.Connection = new SqlConnection("Server=DNEPR\\SQL2000; Database=Monkey; User ID=sa; Password=sqlserver;Trusted_Connection=False");
			sql.Connection.Open();

			targets = new string[] {"ready"};
			tw = new Typewriter(targets[0]);
			for (int i = 0; i < targets.Length; i++)
			{
				tw.SetTarget(targets[i]);
				Console.WriteLine("Monkey is typing: \"" + targets[i]+"\"");
				tw.target.SubscribeTargetReachedEvent(new TargetReachedEventHandler(Success));
				for (int k = 0; k < count; k++)
				{
					off = true;
					while (off)
						tw.keyboard.PressButton();
				}
			}
			sql.Connection.Close();
		}

		private static void Success()
		{
			sql.CommandText =
				@"INSERT INTO stats1
					VALUES
					(@seq, @iter)";

			sql.Parameters["@seq"].Value = tw.target.targetword;
			sql.Parameters["@iter"].Value = tw.counter;

			sql.ExecuteNonQuery();
			tw.counter = 0;
			off = false;
		}

		private static void ClearDatabase()
		{
			SqlCommand cmd = new SqlCommand();
			cmd.CommandText = @"DELETE FROM stats1";

			DataManager.ExecuteCmd(cmd);
		}
	}
}